package com.example.shixun1.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.example.shixun1.Fragment.HeadlinesFragment;
import com.example.shixun1.Fragment.MallFragment;
import com.example.shixun1.Fragment.MeFragment;
import com.example.shixun1.R;
import com.google.android.material.bottomnavigation.BottomNavigationView;

public class LoginActivity extends AppCompatActivity {
    private EditText etUsername, etPassword;
    private SharedPreferences userPrefs;
    private SharedPreferences loginStatePrefs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 初始化SharedPreferences
        userPrefs = getSharedPreferences("users", MODE_PRIVATE);
        loginStatePrefs = getSharedPreferences("login_state", MODE_PRIVATE);

        // 检查登录状态
        if (loginStatePrefs.getBoolean("is_logged_in", false)) {
            redirectToMain();
            return;
        }

        setContentView(R.layout.activity_login);
        setupViews();
    }

    private void setupViews() {
        etUsername = findViewById(R.id.et_login_username);
        etPassword = findViewById(R.id.et_login_password);

        Button btnLogin = findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(v -> validateCredentials());

        TextView tvRegister = findViewById(R.id.tv_register_link);
        tvRegister.setOnClickListener(v -> {
            startActivity(new Intent(this, RegisterActivity.class));
        });
    }

    private void validateCredentials() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请输入用户名和密码", Toast.LENGTH_SHORT).show();
            return;
        }

        String savedPassword = userPrefs.getString(username + "_password", "");
        if (password.equals(savedPassword)) {
            // 保存登录状态
            loginStatePrefs.edit()
                    .putBoolean("is_logged_in", true)
                    .putString("current_user", username)
                    .apply();

            redirectToMain();
        } else {
            Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
        }
    }

    private void redirectToMain() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }
}